<!DOCTYPE html>
<html>

<head>
    <title>每日数据统计</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 20px;
        }

        #app {
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        h1 {
            color: #333;
            margin-bottom: 20px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        th,
        td {
            padding: 12px;
            text-align: center;
            border-bottom: 1px solid #ddd;
        }

        th {
            background-color: #f8f9fa;
            font-weight: bold;
        }

        .status-indicator {
            display: inline-block;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            vertical-align: middle;
        }

        .status-enabled {
            background-color: #4CAF50;
        }

        .status-disabled {
            background-color: #F44336;
        }

        .disabled {
            position: relative;
        }

        .disabled::after {
            content: '';
            position: absolute;
            left: 0;
            top: 50%;
            width: 100%;
            height: 1px;
            background: #999;
            transform: rotate(-5deg);
        }

        tr:hover {
            background-color: #f5f5f5;
        }

        tr:nth-child(even) {
            background-color: #f9f9f9;
        }

        .add-btn {
            background: linear-gradient(135deg, #6a11cb, #2575fc);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .add-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }

        button {
            background-color: #2575fc;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            margin-right: 5px;
            transition: all 0.3s ease;
        }

        button:hover {
            background-color: #1a5bbf;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 1000;
        }

        .modal-backdrop {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .modal-content {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            width: 400px;
        }

        .modal-content h2 {
            margin-top: 0;
            color: #333;
        }

        .modal-content label {
            display: block;
            margin-bottom: 10px;
            color: #666;
        }

        .modal-content input {
            width: 100%;
            padding: 8px;
            margin-top: 4px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .modal-content button {
            margin-right: 10px;
        }

        .sort-arrow {
            display: inline-block;
            width: 0;
            height: 0;
            border-left: 5px solid transparent;
            border-right: 5px solid transparent;
            margin-left: 5px;
        }

        .sort-arrow.asc {
            border-bottom: 5px solid #666;
        }

        .sort-arrow.desc {
            border-top: 5px solid #666;
        }

    </style>
</head>

<body>
    <div id="app">
        <h1>每日数据统计</h1>
        <button class="add-btn" id="add-btn">添加记录</button>
        <table>
            <thead>
                <tr>
                    <th>序号</th>
                    <th>日期</th>
                    <th>产品名称</th>
                    <th>总产量</th>
                    <th>平均效率</th>
                    <th>入库效率</th>
                    <th>合并档</th>
                    <th>DLCC</th>
                    <th>漏电NG</th>
                    <th>漏电失效</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="data-body"></tbody>
        </table>

        <div class="modal">
            <div class="modal-backdrop"></div>
            <div class="modal-content">
                <h2>添加记录</h2>
                <form id="config-form">
                    <label>日期: <input type="date" id="config-date" required></label>
                    <label>班次: <input type="text" id="config-shift" required></label>


                    <label>产品名称: <input type="text" id="config-product" required></label>
                    <label>总产量: <input type="number" id="config-total" required></label>
                    <!-- 设置输入框支持小数 -->
                    <label>平均效率: <input type="number" id="config-avg-efficiency" step="0.001" required></label>
                    <label>入库效率: <input type="number" id="config-storage-efficiency" step="0.001" required></label>
                    <label>合并档: <input type="text" id="config-merge" required></label>
                    <label>DLCC: <input type="number" id="config-dlcc" required></label>
                    <label>漏电合并档: <input type="number" id="config-leak-ng" required></label>
                    <label>漏电失效: <input type="number" id="config-leak-fail" required></label>
                    <button type="submit">保存</button>
                    <button type="button" id="cancel-btn">取消</button>
                </form>
            </div>
        </div>
    </div>
    <script>
        // 添加排序功能
        const sortTable = (columnIndex, order) => {
            const table = document.querySelector('table');
            const tbody = table.querySelector('tbody');
            const rows = Array.from(tbody.querySelectorAll('tr'));

            rows.sort((a, b) => {
                const aValue = a.querySelectorAll('td')[columnIndex].textContent;
                const bValue = b.querySelectorAll('td')[columnIndex].textContent;

                // 尝试将值转换为数字
                const numA = parseFloat(aValue);
                const numB = parseFloat(bValue);

                // 如果两个值都是有效数字，则按数字排序
                if (!isNaN(numA) && !isNaN(numB)) {
                    return order === 'asc' ? numA - numB : numB - numA;
                }
                // 否则按字符串排序
                else {
                    return order === 'asc' ? aValue.localeCompare(bValue) : bValue.localeCompare(aValue);
                }
            });

            tbody.innerHTML = '';
            rows.forEach(row => tbody.appendChild(row));
        };


        // 为表头添加点击事件
        const headers = document.querySelectorAll('th');
        headers.forEach((header, index) => {
            header.addEventListener('click', () => {
                const currentOrder = header.dataset.order || 'asc';
                sortTable(index, currentOrder);
                header.dataset.order = currentOrder === 'asc' ? 'desc' : 'asc';
            });
        });
        document.addEventListener('DOMContentLoaded', function () {
            const modal = document.querySelector('.modal');
            const addBtn = document.getElementById('add-btn');
            const cancelBtn = document.getElementById('cancel-btn');
            const configForm = document.getElementById('config-form');
            const dataBody = document.getElementById('data-body');
            let currentEditId = null;

            // 加载每日统计数据
            function loadDailyStats() {
                fetch('/api/daily_stats')
                    .then(response => response.json())
                    .then(data => {
                        renderDailyStats(data);
                    })
                    .catch(error => console.error('Error:', error));
            }

            // 渲染每日统计数据到表格
            function renderDailyStats(stats) {
                dataBody.innerHTML = '';
                stats.forEach((stat, index) => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
            <td>${index + 1}</td>
            <td>${stat.date}-${stat.shift}</td>
            <td>${stat.BinFileName}</td>
            <td>${stat.sum_IvGrade}</td>
            <td>${stat.avg_eta}</td>
            <td>${stat.ru_eta}</td>
            <td>${stat.hbd}</td>
            <td>${stat.dlcc}</td>
            <td>${stat.IRev2_B}</td>
            <td>${stat.IRev2_Fail}</td>
            <td>
                <button class="edit-btn" data-id="${stat.id}">编辑</button>
                <button class="delete-btn" data-id="${stat.id}">删除</button>
            </td>
        `;
                    dataBody.appendChild(row);
                });

                // 添加编辑按钮事件
                document.querySelectorAll('.edit-btn').forEach(btn => {
                    btn.addEventListener('click', function () {
                        const id = this.getAttribute('data-id');
                        editDailyStat(id);
                    });
                });

                // 添加删除按钮事件
                document.querySelectorAll('.delete-btn').forEach(btn => {
                    btn.addEventListener('click', function () {
                        const id = this.getAttribute('data-id');
                        deleteDailyStat(id);
                    });
                });
            }

            // 编辑每日统计
            function editDailyStat(id) {
                fetch(`/api/daily_stats`)
                    .then(response => response.json())
                    .then(stats => {
                        const stat = stats.find(s => s.id == id);
                        if (stat) {
                            currentEditId = id;
                            // 将日期转换回YYYY-MM-DD格式
                            const formattedDate = stat.date.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
                            document.getElementById('config-date').value = formattedDate;
                            document.getElementById('config-shift').value = stat.shift;
                            document.getElementById('config-product').value = stat.BinFileName;
                            document.getElementById('config-total').value = stat.sum_IvGrade;
                            document.getElementById('config-avg-efficiency').value = stat.avg_eta;
                            document.getElementById('config-storage-efficiency').value = stat.ru_eta;
                            document.getElementById('config-merge').value = stat.hbd;
                            document.getElementById('config-dlcc').value = stat.dlcc;
                            document.getElementById('config-leak-ng').value = stat.IRev2_B;
                            document.getElementById('config-leak-fail').value = stat.IRev2_Fail;
                            document.querySelector('.modal-content h2').textContent = '编辑记录';
                            modal.style.display = 'block';
                        }
                    })
                    .catch(error => console.error('Error:', error));
            }

            // 删除每日统计
            function deleteDailyStat(id) {
                if (confirm('确定要删除此记录吗？')) {
                    fetch('/api/daily_stats', {
                        method: 'DELETE',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ id: id })
                    })
                        .then(response => {
                            if (response.ok) {
                                loadDailyStats();
                            }
                        })
                        .catch(error => console.error('Error:', error));
                }
            }

            // 添加按钮点击事件
            addBtn.addEventListener('click', function () {
                currentEditId = null;
                configForm.reset();
                document.querySelector('.modal-content h2').textContent = '添加记录';
                modal.style.display = 'block';
            });

            // 取消按钮点击事件
            cancelBtn.addEventListener('click', function () {
                modal.style.display = 'none';
            });

            // 表单提交事件
            // 在表单提交事件中
            configForm.addEventListener('submit', function (e) {
                e.preventDefault();

                // 获取日期并格式化
                const dateInput = document.getElementById('config-date').value;
                const formattedDate = dateInput.replace(/-/g, '');

                const statData = {
                    date: formattedDate,
                    shift: document.getElementById('config-shift').value,
                    BinFileName: document.getElementById('config-product').value,
                    sum_IvGrade: document.getElementById('config-total').value,
                    avg_eta: document.getElementById('config-avg-efficiency').value,
                    ru_eta: document.getElementById('config-storage-efficiency').value,
                    hbd: document.getElementById('config-merge').value,
                    dlcc: document.getElementById('config-dlcc').value,
                    IRev2_B: document.getElementById('config-leak-ng').value,
                    IRev2_Fail: document.getElementById('config-leak-fail').value
                };

                if (currentEditId) {
                    statData.id = currentEditId;
                }

                fetch('/api/daily_stats', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(statData)
                })
                    .then(response => {
                        if (!response.ok) {
                            return response.json().then(data => {
                                throw new Error(data.error || '保存失败');
                            });
                        }
                        return response.json();
                    })
                    .then(data => {
                        modal.style.display = 'none';
                        loadDailyStats();
                    })
                    .catch(error => {
                        alert(error.message);
                        console.error('Error:', error);
                    });
            });

            // 点击模态框背景关闭
            document.querySelector('.modal-backdrop').addEventListener('click', function () {
                modal.style.display = 'none';
            });

            // 初始加载数据
            loadDailyStats();
        });
    </script>

</body>

</html>